<%= stylesheet 'jquery' %>
<%= javascript :header, 'daterangepicker' %>

<%= title "Loading Search `#{@search.title}`..." -%>

<script type="text/javascript" charset="utf-8">
  $(function() {
    var loadSavedSearch = function(json) {
      var data = JSON.parse(json);
      if (data) {
        $('#searches').hide();

        rule.searchUI({
          cssClass: "update-saved-search",
          buttonTitle: "Update & Run"
        }, function() {
          rule.build(data.search);

          $('#title-header').replaceWith('<div class="edit edit-search-title" id="title-header">'+sanitize data.title+'</div><span class="sub-title">(click to edit)</span>');

          $('.edit-search-title').editable(baseuri + "/saved/searches/title", {
            height: '20px',
            method: 'POST',
            width: '180px',
            name: "title",
            indicator: '<img src="<%= Snorby::CONFIG[:baseuri] %>/images/icons/pager.gif">',
            data: function(value) {
              var retval = value.replace(/<br[\s\/]?>/gi, '\n');
              return retval;
            },
            submitdata : function() {
              return { id: data.id, authenticity_token: csrf };
            }
          });

          $('#form-actions').append('<button class="warning default"><span class="sub-title">Cancel</span></button>');

          $('button.warning').bind('click', function(e) {
            e.preventDefault();
            window.location = baseuri + '/saved/searches';
          });

          $('button.update-saved-search').click(function(e) {
            e.preventDefault();

            rule.submit(function(ss) {

              $.ajax({
                url: baseuri + '/saved/searches/'+data.id,
                type: "POST",
                dataType: "json",
                global: false,
                cache: false,
                data: {
                id: data.id,
                authenticity_token: csrf,
                search: {
                  match_all: ss.match_all,
                  search: ss.items
                }}
              });

            }, {
              title: data.title,
              search_id: data.id
            });
          });
        });

        $(this).removeClass('loading').text('Edit');
      };
    };

    var rule = new SearchRule('<%= escape_javascript Snorby::Search.json.html_safe %>');
    loadSavedSearch('<%= escape_javascript @search.to_json.html_safe %>');
  });
</script>
